<template>
  <div id="openlayersContainer" ref="openlayersContainer"></div>
  <div class="top-line">
    <div class="search-container">
      <div>请输入城市名称</div>
      <el-input v-model="cityName" style="width: 240px;height: 40px;" placeholder="请输入城市名称"
        @keyup.enter="handleSearchCity()" />
    </div>

    <el-select v-model="drawType" placeholder="请选择绘制图形" size="large" style="width: 240px"
      @change="handleDrawTypeChange">
      <el-option v-for="item in drawTypeList" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-select v-model="iconType" placeholder="请选择图标类型" size="large" style="width: 240px">
      <el-option v-for="item in iconTypeList" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
  </div>
  <div class="button-container ">
    <!-- <button @click="clearLine">清除line</button>
    <button @click="startDraw">开始绘图</button>
    <button @click="stopDraw">停止绘图</button> -->
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile.js'
import Map from 'ol/Map.js'
import XYZ from 'ol/source/XYZ.js'
import 'ol/ol.css'
import Feature from 'ol/Feature.js'
import Point from 'ol/geom/Point.js';
import VectorSource from 'ol/source/Vector.js'
import VectorLayer from 'ol/layer/Vector.js'
import Style from 'ol/style/Style.js'
import Icon from 'ol/style/Icon.js'
import CircleStyle from 'ol/style/Circle.js'
import Fill from 'ol/style/Fill.js'
import Text from 'ol/style/Text.js'
import Stroke from 'ol/style/Stroke.js'
import { LineString } from 'ol/geom';
import GeoJSON from 'ol/format/GeoJSON.js'
import Draw from 'ol/interaction/Draw.js'
import { click } from 'ol/events/condition';
import { defaults } from 'ol/control/defaults';
import ScaleLine from 'ol/control/ScaleLine.js';
import MousePosition from 'ol/control/MousePosition.js';
import Fullscreen from 'ol/control/FullScreen.js';
import Zoom from 'ol/control/Zoom';
let map = null

const cityName = ref('北京')
const iconType = ref('')
const drawType = ref('')
const drawTypeList = [
  { label: '直线', value: 'LineString' },
  { label: '多边形', value: 'Polygon' },
  { label: '圆形', value: 'Circle' },
  { label: '自由曲线', value: 'freehand' },
  { label: '清除画图', value: 'clear' }
]
const iconTypeList = [
  { label: '充电站', value: 'chargingStation' },
  { label: '公交站', value: 'busStation' },
  { label: '停车场', value: 'parking' },
  { label: '清除标记', value: 'clear' },
]

const keyList = [
  'dbf077ba73964a4e9fce0f13e0525c69',
  'ec85bffce701cbb5e52fb7241c85b32a',
  'c1db9fc26aebb8832819b05eaa6bdd05',
  'f48b7ceeeb76c5a2c31439a41810af15',
  'ee20013ff03e7d98b23e1251bc0b7cea'
]

let cityLayer = new VectorLayer({
  className: 'cityLayer',
})
// let cityLocation = null
// let adCode = null

onMounted(async () => {
  map = new Map({
    target: 'openlayersContainer',
  });
  map.setView(view)
  searchCity(cityName.value)
  map.addLayer(gaodeLayer);
  map.addLayer(drawLayer)
  map.addLayer(cityLayer)
  map.getView().on('change:resolution', function () {
    const currentZoom = map.getView().getZoom();
    const currentResolution = map.getView().getResolution();
    if(currentZoom>10){
      cityLayer.setVisible(false)
      drawLayer.setVisible(false)
    } else {
      cityLayer.setVisible(true)
      drawLayer.setVisible(true)

    }

    console.log(`当前缩放级别: ${currentZoom}, 当前分辨率: ${currentResolution}`);
  });
})

const view = new View({
  center: [114.3165, 30.5264],
  zoom: 5,
  maxZoom: 18,
  minZoom: 2,
  projection: 'EPSG:4326'
})
// 高德地图
const gaodeSourse = new XYZ({
  // 高德地图
  url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
})
const gaodeLayer = new TileLayer({
  source: gaodeSourse
})

const searchCity = async (name) => {

  const _temp = await fetch(`http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${name}","queryType":12,"start":0,"count":10,"specify":"156110108"}&type=query&tk=${keyList[Math.floor(Math.random() * 5)]}`)
  const _res = await _temp.json()
  if (_res.count != 1) {
    alert('请输入正确的城市名')
    cityName.value = ''
    return
  }
  let adCode = (_res.area.adminCode + '').slice(3);
  let cityLocation = [Number(_res.area.lonlat.split(',')[0]), Number(_res.area.lonlat.split(',')[1])]

  cityLayer.setSource(new VectorSource({
    url: `https://geo.datav.aliyun.com/areas_v3/bound/${adCode}.json`,
    format: new GeoJSON(),
  }))

  cityLayer.setStyle(new Style({
    fill: new Fill({
      color: 'rgba(255,0,0,0.5)'
    }),
    stroke: new Stroke({
      color: 'red',
      width: 2
    })
  }))
  view.setCenter(cityLocation)
  view.setZoom(9)
}

const handleSearchCity = () => {
  console.log(cityName.value)
  if (cityName.value) {
    searchCity(cityName.value)
    // fetch(`https://restapi.amap.com/v3/geocode/geo?key=${keyList[Math.floor(Math.random() * 5)]}&address=${cityName.value}`)
    // fetch(`http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${cityName.value}","queryType":12,"start":0,"count":10,"specify":"156110108"}&type=query&tk=${keyList[Math.floor(Math.random() * 5)]}`)
    // .then(res => res.json())
    // .then(res => {
    //   // return
    //   if (res.count === 1) {
    //     map.setView(new View({
    //       center: [Number(res.area.lonlat.split(',')[0]), Number(res.area.lonlat.split(',')[1])],
    //       zoom: 11,
    //       projection: 'EPSG:4326'
    //     }))
    //   } else {
    //     
    //   }
    // })
  }
}

const drawVectorSource = new VectorSource({})
const drawLayer = new VectorLayer({
  source: drawVectorSource,
  className: 'lineLayer',
  style: new Style({
    stroke: new Stroke({
      color: 'red',
      width: 6
    })
  })
})
let draw = null
const handleDrawTypeChange = () => {
  if (drawType.value == 'clear') {
    drawLayer.getSource().clear()
    drawType.value = ''
    map.removeInteraction(draw)
  }
  else {
    map.removeInteraction(draw)
    // drawLayer.getSource().clear()
    draw = null
    if (drawType.value == 'freehand') {
      draw = new Draw({
        source: drawVectorSource,
        type: 'LineString',
        freehand: true
      })
    } else {
      draw = new Draw({
        source: drawVectorSource,
        type: drawType.value
      })
    }
    map.addInteraction(draw)

  }

}



</script>

<style>
* {
  margin: 0;
  padding: 0;
}

#openlayersContainer {
  width: 100vw;
  height: 100vh;

}

.button-container {
  position: absolute;
  left: 100px;
  top: 100px;
  z-index: 1;
}

.top-line {
  width: 100%;
  height: 80px;
  position: absolute;
  top: 0;
  z-index: 99;
  background: blue;
  display: flex;
  align-items: center;
  gap: 100px;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 30px;
  color: #fff;
  padding-left: 30px;
}
</style>
